import { Dispatch, Grade, State } from './types';
import navigator from '../../../../util/navigator';
import { LANDSCAPE_ROUTES, PORTRAIT_ROUTES } from '../../../../config/route';
import { CourseApi } from '../../../../api';
import { Commodity } from '../../../../api/course/getDiscoveryPage';

let dispatch: Dispatch;
let state: State;

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const setData = (value: any): void => {
  dispatch({ type: 'SET_DATA', value });
};

export const setIsShowSelectGrade = (value: boolean): void => {
  dispatch({ type: 'SET_IS_SHOW_SELECT_GRADE', value });
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

// 获取数据
export const getData = async (gradeId?: number): Promise<void> => {
  const { currentGrade } = state;
  const res = await CourseApi.getDiscoveryPage({
    gradeId: gradeId || currentGrade.id
  });
  const { code, data } = res;
  if (code !== 0 || !data) return;

  setData(data);
};

const getTargetInfo = (
  target: string
): { pageName: string; params: { [key: string]: any } } => {
  let pageName = '';
  let params: { [key: string]: any } = {};
  const reg = target.match(/\/\/(\S*)\?/);

  if (reg && reg.length > 1) {
    // eslint-disable-next-line prefer-destructuring
    pageName = reg[1];
  }

  const paramUrl = target.match(/\?(\S*)/);

  if (paramUrl && paramUrl.length > 1) {
    if (typeof paramUrl[1] === 'string') {
      paramUrl[1].split('&').forEach((item): void => {
        const keyValue = item.split('=');
        if (keyValue.length === 2) {
          params = {
            ...params,
            [keyValue[0]]: Number.isNaN(Number(keyValue[1]))
              ? keyValue[1]
              : Number(keyValue[1])
          };
        }
      });
    }
  }

  return { pageName, params };
};

export const onPressBanner = (target: string): void => {
  setIsShowSelectGrade(false);
  if (target.indexOf('https') !== -1) {
    navigator.push('WebView', { url: target });
    return;
  }
  const { pageName, params } = getTargetInfo(target);
  const isExistRouteName =
    !!LANDSCAPE_ROUTES.find((routeName): boolean => routeName === pageName) ||
    !!PORTRAIT_ROUTES.find((routeName): boolean => routeName === pageName);
  if (isExistRouteName) {
    navigator.push(pageName, params);
  }
};

export const onPressSpu = (spu: Commodity): void => {
  setIsShowSelectGrade(false);
  navigator.push('SpuDetail', { commodityId: spu.id });
};

export const setCurrentGrade = (value: Grade): void => {
  dispatch({ type: 'SET_CURRENT_GRADE', value });
  getData(value.id);
};
